package com.leoman.post.controller;

import com.leoman.category.entity.Category;
import com.leoman.category.service.CategoryService;
import com.leoman.common.controller.common.GenericEntityController;
import com.leoman.common.factory.DataTableFactory;
import com.leoman.entity.Constant;
import com.leoman.entity.FileBo;
import com.leoman.exception.GeneralExceptionHandler;
import com.leoman.message.entity.Message;
import com.leoman.message.service.MessageService;
import com.leoman.post.entity.PostBase;
import com.leoman.post.entity.PostComment;
import com.leoman.post.entity.PostImage;
import com.leoman.post.service.PostBaseService;
import com.leoman.post.service.PostCommentService;
import com.leoman.post.service.PostImageService;
import com.leoman.post.service.UserChangeService;
import com.leoman.post.service.impl.PostBaseServiceImpl;
import com.leoman.sensitivewords.service.SensitiveWordsService;
import com.leoman.user.entity.UserInfo;
import com.leoman.user.service.UserService;
import com.leoman.userapi.service.UserIntegralService;
import com.leoman.userchange.entity.UserChange;
import com.leoman.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 蔡琦 on 2016/6/27 0027.
 */
@Controller
@RequestMapping(value = "admin/userPost")
public class UserPostController extends GenericEntityController<PostBase, PostBase, PostBaseServiceImpl> {

    @Autowired
    private PostBaseService postBaseService;

    @Autowired
    private UserService userService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private PostImageService postImageService;

    @Autowired
    private UserIntegralService userIntegralService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private SensitiveWordsService sensitiveWordsService;

    @Autowired
    private PostCommentService postCommentService;

    @Autowired
    private UserChangeService userChangeService;

    /**
     * 列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/index")
    public String index() {
        return "post/userPostList";
    }

    /**
     * 查询列表
     */
    @RequestMapping(value = "/list")
    public void list(HttpServletResponse response,
                     String content,
                     String mobile,
                     Long category,
                     Integer status,
                     Integer essence,
                     Integer draw,
                     Integer start,
                     Integer length) {
        try {

            int pageNum = getPageNum(start, length);

            Page<PostBase> page = postBaseService.page(content, mobile, category, status, essence, Constant.POST_TYPE_003, pageNum, length);
            List<PostComment> postCommentList;
            List<UserChange> userChangeList;
            for (PostBase postBase : page.getContent()) {

                // 查询帖子评论数
                postCommentList = postCommentService.findByPostId(postBase.getId());
                postBase.setComment(postCommentList != null ? postCommentList.size() : 0);

                // 查询帖子点赞数
                userChangeList = userChangeService.findByPostId(postBase.getId());
                postBase.setPraise(userChangeList != null ? userChangeList.size() : 0);
            }

            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    public String add() {

        return "post/userPostAdd";
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail")
    public String detail(Long postId, Model model) {

        PostBase postBase = postBaseService.queryByPK(postId);
        List<PostImage> postImageList = postImageService.findList(postId, Constant.POST_TYPE_003);
        for (PostImage postImage : postImageList) {
            if (StringUtils.isNotEmpty(postImage.getUrl())) {
                postImage.setUrl(ImageUtil.clearUploadUrl(postImage.getUrl()));
            }
        }
        if (StringUtils.isNotEmpty(postBase.getUrl())) {
            postBase.setUrl(ImageUtil.clearUploadUrl(postBase.getUrl()));
        }

        model.addAttribute("postBase", postBase);
        model.addAttribute("postImageList", postImageList);

        return "post/userPostDetail";
    }

    /**
     * 查询主创列表
     */
    @RequestMapping(value = "/creatorList")
    @ResponseBody
    public List<UserInfo> creatorList() {

        return userService.findByStatus();
    }

    /**
     * 查询帖子分类列表
     */
    @RequestMapping(value = "/categoryList")
    @ResponseBody
    public List<Category> categoryList() {

        return categoryService.findType(Constant.CATEGORY_TYPE_001);
    }

    /**
     * 上传缓存图片
     */
    @RequestMapping("/addTempImage")
    @ResponseBody
    public PostImage addTempImage(MultipartRequest multipartRequest) {
        PostImage image = new PostImage();

        try {
            MultipartFile multipartFile = multipartRequest.getFile("tempImage");

            // 验证图片格式
            String originalFileName = multipartFile.getOriginalFilename().toLowerCase();
            String fileType = originalFileName.substring(originalFileName.indexOf("."));

            List<String> list = new ArrayList<>();
            list.add(".jpg");
            list.add(".gif");
            list.add(".jpeg");
            list.add(".png");
            list.add(".bmp");

            if (!list.contains(fileType)) {
                return image;
            }

            FileBo fileBo = FileUtil.save(multipartFile, true);
            image.setUrl(fileBo.getPath());
            image.setSuolue(fileBo.getSuoluePath());
            image.setWidth(fileBo.getWidth());
            image.setHeight(fileBo.getHeight());
            image.setType(Constant.POST_TYPE_003);

            postImageService.save(image);
            image.setUrl(ImageUtil.clearUploadUrl(fileBo.getPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return image;
    }


    /**
     * 设置、取消精华
     */
    @RequestMapping(value = "/isEssence")
    @ResponseBody
    public Integer isEssence(Long postId, Integer essence) {

        PostBase postBase = postBaseService.queryByPK(postId);
        postBase.setEssence(essence);

        if (essence == 1) {
            //UserPost userPost = userPostService.queryByPK(postBase.getPostId());
            userIntegralService.changeCoin(postBase.getUserInfo(), "帖子被加精华", 5);

            // 新增加精消息
            Message message = new Message();
            message.setUserId(postBase.getUserInfo().getId());
            message.setPostId(postId);
            message.setType(1);
            message.setToObject("0");
            message.setTitle("帖子被加精华");
            message.setContent("你的帖子太棒了，被加精，获得5个馒头");
            messageService.save(message);
        }

        postBaseService.update(postBase);

        return 1;
    }

    /**
     * 设置、取消置顶
     */
    @RequestMapping(value = "/isStick")
    @ResponseBody
    public Integer isStick(Long postId, Integer stick) {

        PostBase postBase = postBaseService.queryByPK(postId);
        postBase.setStick(stick);

        if (stick == 1) {
            //UserPost userPost = userPostService.queryByPK(postBase.getPostId());

            // 新增置顶消息
            userIntegralService.changeCoin(postBase.getUserInfo(), "帖子被置顶", 5);
            Message message = new Message();
            message.setUserId(postBase.getUserInfo().getId());
            message.setPostId(postId);
            message.setType(1);
            message.setToObject("0");
            message.setTitle("帖子被置顶");
            message.setContent("你的帖子太棒了，被置顶，获得5个馒头");
            messageService.save(message);
        }

        postBaseService.update(postBase);

        return 1;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Integer delete(Long postId) {

        return postBaseService.deletePost(postId);
    }

    /**
     * 批量删除
     */
    @RequestMapping("/deleteBatch")
    @ResponseBody
    public Integer deleteBatch(String ids) {
        try {
            // 将界面上的id数组格式的字符串解析成int类型的数组
            Long[] arrayId = JsonUtil.json2Obj(ids, Long[].class);
            for (Long id : arrayId) {
                postBaseService.deletePost(id);
            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Integer save(Long creatorId,
                        Long category,
                        String description,
                        String tempAddImageIds1,
                        String tempDelImageIds) {

        // 过滤敏感字符
        description = sensitiveWordsService.replaceWord(description);

        return postBaseService.saveUserPost(creatorId, category, description, tempAddImageIds1, tempDelImageIds);
    }
}
